﻿using BasicInformation.ApiRead.Application.Command.Storage;
using BasicInformation.Domain;
using BasicInformation.Dtos;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using Dapper;
using MediatR;
using System.Text;

namespace BasicInformation.ApiRead.Application.Handler.Storage
{
    public class GetStorageHandler : IRequestHandler<GetStorageCommand, ApiPaging<StorageDTO>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<GetStorageHandler> logger;

        public GetStorageHandler(DatabaseContext db, ILogger<GetStorageHandler> logger)
        {
            this.db = db;
            this.logger = logger;
        }
        public async Task<ApiPaging<StorageDTO>> Handle(GetStorageCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<StorageDTO> result = new ApiPaging<StorageDTO>();
            StringBuilder sql = new StringBuilder();
            StringBuilder countSql = new StringBuilder();

            sql.Append(@"SELECT
                            a.StorageId,
                            a.StorageCode,
                            a.StorageName,
                            a.StorageCapacity,
                            a.StorageAdder,
                            b.Department_Id,
                            b.Department_Name,
                            c.User_WorkCode,
                            c.User_Name,
                            a.LocationNumder,
                            a.StorageState,
                            a.LoginUserName,
                            a.CreatTime 
                        FROM storagemodel a
                        LEFT JOIN departments b 
                            ON a.Department_Id = b.Department_Id COLLATE utf8mb4_0900_ai_ci 
                        LEFT JOIN users c 
                            ON a.User_WorkCode = c.User_WorkCode COLLATE utf8mb4_0900_ai_ci
                        WHERE a.IsDel = 0");
            countSql.Append(@"  SELECT COUNT(*) FROM storagemodel");
            sql.Append(@"   ORDER BY a.CreatTime LIMIT @size OFFSET @offset");


            // 正确设置模糊查询参数
            var parameters = new
            {
                offset = (request.index - 1) * request.size,
                size = request.size
            };
            try
            {
                // 执行查询
                var pageData = await db.DapperConnection.QueryAsync<StorageDTO>(sql.ToString(), parameters);
                //执行总页查询
                int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);
                //计算总页数
                int totalPage = (int)Math.Ceiling(totalCount / (double)request.size);

                // 设置返回结果
                result.Msg = "工单仓库管理查询成功";
                result.Code = ApiEnum.OK;
                result.Data = pageData.ToList();
                result.TotalCount = totalCount;
                result.TotalPCount = totalPage;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "查询工单仓库管理时发生错误");
                result.Msg = "查询工单仓库管理时发生错误";
                result.Code = ApiEnum.Fail;
            }
            return await Task.FromResult(result);
        }
    }
}